import React, {PureComponent} from 'react'

import PropTypes from 'prop-types'
import './index.scss'

/**
* @PureComponent 用于较少修改组件时，省略了shouldComponentUpdate
 * 可以浅比较 props 和 state 是否有变化,至于为什么不深比较?因为那样效率可能会比全部render还低
 * https://segmentfault.com/a/1190000018549047
* */

class Avatar extends PureComponent {
  /**
   * @size => [default, big, small]
   * @className => 自定义样式类
   * */
  static propTypes = {
    avatar: PropTypes.string.isRequired,
    size: PropTypes.string,
    className: PropTypes.string,
    round: PropTypes.string
  }

  state = {
    bgArr: ['#cccccc', '#cd5656', '#60c957', '#5a67e0', '#db5bee'],
    bgColor: ''
  }

  componentDidMount() {
    // 随机生成头像背景
    const {bgArr} = this.state;
    const r = Math.floor(Math.random() * bgArr.length);
    this.setState({
      bgColor: bgArr[r]
    })
  }

  render() {
    const {size, avatar, className, round} = this.props;
    const {bgColor} = this.state;

    return (
      <div
        className={
          `avatar-container avatar-${size ? size : 'default'} ${className} ${round}`
        }
        style={{'background': bgColor}}
      >
        {avatar ? avatar : '头像'}
      </div>
    );
  }

}

export default Avatar